package com.css.bjdt_core.executive;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.mvel2.MVEL;

import com.css.bjdt_core.cell.entity.Cell;
import com.css.bjdt_core.cell.entity.CellData;
import com.css.bjdt_core.executive.report.ReportCache;
import com.css.bjdt_core.report.entity.RptTemplateUnitRela;
import com.css.bjdt_core.util.ReportConstant;

public class CalcExecutor extends DefaultExecutor {

	private static Log logger = LogFactory.getLog(CalcExecutor.class);

	private ReportCache cache = null;

	@Override
	public String execute(Cell cell, RptTemplateUnitRela templateUnitRela) {
		List<CellData> list = (List<CellData>) cache
				.getCellData(templateUnitRela.getReportUnitId() + templateUnitRela.getTemplateId());
		String calcExp = cell.getCalcExp().getCellExp();
		String calcExpType = cell.getCalcExp().getFormulaType();
		String result = "0";
		if (calcExp != null) {
			for (CellData cellData : list) {
				StringBuilder key = new StringBuilder();
				key.append("[").append(cellData.getRowNum(calcExpType)).append(ReportConstant.SPLIT_OPERATOR)
						.append(cellData.getColNum(calcExpType)).append("]");
				if (cellData.getCellValue() != null && calcExp.contains(key.toString()))
					calcExp = calcExp.replace(key, cellData.getCellValue());
			}
			try {
				result = MVEL.eval(calcExp).toString();
			} catch (Exception e) {
				logger.debug("executeExp cell id=" + cell.getCellId());
				logger.debug("error exp is " + calcExp);
			}
		}
		return result;
	}

}
